var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { hasImports, findAndRemoveImports, resolveAllImports } from '@mintlify/common';
import { preparseMdx, getFileListSync } from '@mintlify/prebuild';
import { promises as _promises } from 'fs';
import { outputFile } from 'fs-extra';
import { join } from 'path';
import { CMD_EXEC_PATH, NEXT_PROPS_PATH } from '../../constants.js';
import { getSnippets } from './getSnippets.js';
const { readFile } = _promises;
export const generatePagesWithImports = () => __awaiter(void 0, void 0, void 0, function* () {
    const snippets = yield getSnippets();
    const pageFilenames = getFileListSync(CMD_EXEC_PATH).filter((file) => file.endsWith('.mdx') && !file.startsWith('_snippets/') && !file.startsWith('snippets/'));
    yield Promise.all(pageFilenames.map((pageFilename) => __awaiter(void 0, void 0, void 0, function* () {
        const sourcePath = join(CMD_EXEC_PATH, pageFilename);
        const contentStr = (yield readFile(sourcePath)).toString();
        try {
            const importsResponse = yield findAndRemoveImports(contentStr);
            if (hasImports(importsResponse)) {
                importsResponse.content = yield preparseMdx(importsResponse.content, CMD_EXEC_PATH, sourcePath);
                const content = yield resolveAllImports({
                    snippets,
                    fileWithImports: Object.assign(Object.assign({}, importsResponse), { filename: pageFilename }),
                });
                const targetPath = join(NEXT_PROPS_PATH, pageFilename);
                yield outputFile(targetPath, content, {
                    flag: 'w',
                });
            }
        }
        catch (err) {
            console.log('Error generating pages with imports');
            console.log(pageFilename);
            console.log(err);
        }
    })));
});
